package com.code.translate.utils;

import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ggh
 * @date 2022/10/16
 */
public class CookieUtils {
    public static Map<String, Cookie> parseResponseCookie(List<String> cookieList) {
        Map<String, Cookie> cookieMap = new HashMap<>(cookieList.size());
        for (String cookieStr : cookieList) {
            String[] cookies = cookieStr.split(";");
            String[] cookieNameValue = cookies[0].split("=");
//            String[] cookieMaxAge = cookies[1].split("=");
//            String[] cookiePath = cookies[2].split("=");

            String cookieValue = "";
            if (cookieNameValue.length == 2) {
                cookieValue = cookieNameValue[1];
            } else if (cookieNameValue.length > 2) {
                cookieValue = cookies[0].substring(cookies[0].indexOf("=") + 1);
            }
            Cookie cookie = new Cookie(cookieNameValue[0], cookieValue);
            cookieMap.put(cookie.getName(), cookie);
        }
        return cookieMap;
    }

    public static String buildCookie(Cookie... cookieList) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Cookie cookie : cookieList) {
            stringBuffer.append(cookie.getName() + "=" + cookie.getValue() + ";");
        }
        stringBuffer = stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }
}
